
import 'package:dio/dio.dart';
import 'package:fluttertoast/fluttertoast.dart';

import 'base_model.dart';

class ResponseInterceptor extends Interceptor {
  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    if (response.statusCode == 200) {
      try {
        var res = BaseModel.fromJson(response.data);
        if (res.errorCode == 0) {
          if(res.data != null){
            handler.next(Response(requestOptions: response.requestOptions,data: res.data));
          } else {
            handler.next(Response(requestOptions: response.requestOptions, data: true));
          }
        } else if (res.errorCode == -1001) {
          handler.reject(DioException(requestOptions: response.requestOptions, message: '请先登录'));
          Fluttertoast.showToast(msg: '请先登录');
        } else {
          handler.reject(DioException(requestOptions: response.requestOptions, message: res.errorMsg ?? ''));
          Fluttertoast.showToast(msg: res.errorMsg ?? '');

        }
      } catch (e) {
        handler.reject(DioException(requestOptions: response.requestOptions, message: '$e'));
      }
    } else { 
      handler.reject(DioException(requestOptions: response.requestOptions));
    }
  }
}
